/***************************************************************************
 *   Copyright (C) 2008-2009 by Dominik Kapusta       <d@ayoy.net>         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License as        *
 *   published by the Free Software Foundation; either version 2.1 of      *
 *   the License, or (at your option) any later version.                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this program; if not, write to                     *
 *   the Free Software Foundation, Inc.,                                   *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
 ***************************************************************************/


#ifndef IMAGEDOWNLOAD_H
#define IMAGEDOWNLOAD_H

#include <QObject>
#include <QMap>
#include <QCache>
#include <QPixmap>
#include <QNetworkAccessManager>
#include <QPointer>
#include <QUrl>

namespace ImageDownload {


class AvatarManager : public QObject
{
    Q_OBJECT
public:
    static AvatarManager* instance(QObject *parent = 0);

    void imageGet( const QString &imageUrl );
    bool contains( const QString &imageUrl ) const;
    QPixmap* imageFromUrl( const QString &imageUrl ) const;

protected:
    AvatarManager( QObject *parent = 0 );
    ~AvatarManager();

Q_SIGNALS:
    // The change notification signals of the properties
    void imageReady();
    void imageChanged();
    void loadingChanged();
    void imageReadyForUrl(const QString &path);

private slots:
    void requestFinished(QNetworkReply *reply);

private:
    QUrl redirectUrl(const QUrl& possibleRedirectUrl,
                     const QUrl& oldRedirectUrl) const;
    QNetworkAccessManager* createNetworkAccessManager();

    void insertRedirectUrlMap(const QString &oldUrl, const QString &newUrl);
    QString getOriginalUrl(const QString &url);

private:
     static AvatarManager *m_instance;

    QMap<QString, QNetworkAccessManager*> m_connections;
    QCache<QString, QPixmap> m_imageCache;

    QString m_originalUrlString;
    QUrl m_originalUrl;
    QUrl m_urlRedirectedTo;
    QUrl m_baseUrl;

    QMap<QString, QString> m_redirectUrlMap;
};

} // namespace ImageDownload
#endif //IMAGEDOWNLOAD_H
